<template>
  <div class="travel-container">
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-input v-model="searchText" placeholder="请输入景区名称" class="search-input"></el-input>
      <el-button type="primary" @click="handleSearch">搜索</el-button>
    </div>

    <!-- 景区列表 -->
    <div class="scenic-list" v-loading="loading">
      <el-row :gutter="20">
        <el-col :span="8" v-for="item in scenicList" :key="item.id">
          <el-card class="scenic-card">
            <img :src="item.imgUrl" class="scenic-image" @click="goInfo(item.id)">
            <div class="scenic-info">
              <h3>{{ item.name }}</h3>
              <p class="desc">{{ item.info }}</p>
              <div class="price-area">
                <span class="price">{{ item.ticketPrice === 0 ? '免费' : '¥' + item.ticketPrice }}</span>
                <el-button type="primary" size="small" @click="handleBook(item)">立即预订</el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        size="default"
        background
        :default-page-size="6"
        :current-page="currentPage"
        layout="total, prev, pager, next, jumper"
        :total="total"
        :page-count="pageCount"
        @current-change="handlePageChange"
      />
    </div>
  </div>

  <!-- 支付弹窗 -->
  <el-dialog
      title="订单支付"
      v-model="payDialogVisible"
      width="30%">
      <div class="alipay-style-dialog">
        <div class="alipay-header">
          <img src="https://img.alicdn.com/imgextra/i1/O1CN01R0YN9T1nN1BCkqP5Y_!!6000000005072-2-tps-140-140.png" class="alipay-logo">
          <span class="alipay-title">支付宝</span>
        </div>
        <div class="order-details">
          <div class="order-info">
            <p class="order-name">{{ scenicInfo.name }} - 景区门票</p>
            <p class="order-number">订单编号：{{ orderId }}</p>
          </div>
          <div class="order-price">
            <span class="price-symbol">¥</span>
            <span class="price-value">{{ scenicInfo.ticketPrice === 0 ? '0.00' : scenicInfo.ticketPrice.toFixed(2) }}</span>
          </div>
        </div>
        <div class="payment-methods">
          <div class="payment-method-title">支付方式</div>
          <div class="payment-method-item" :class="{ selected: payMethod === 'alipay' }" @click="selectPayMethod('alipay')">
            <div class="method-icon alipay-icon"></div>
            <div class="method-name">支付宝</div>
            <div class="method-check" :class="{ active: payMethod === 'alipay' }"></div>
          </div>
          <div class="payment-method-item" :class="{ selected: payMethod === 'wechat' }" @click="selectPayMethod('wechat')">
            <div class="method-icon wechat-icon"></div>
            <div class="method-name">微信支付</div>
            <div class="method-check" :class="{ active: payMethod === 'wechat' }"></div>
          </div>
        </div>
        <div class="alipay-qrcode">
          <div class="qrcode-container">
            <img style="width: 180px;height: 180px;" :src="require('../assets/vx_pay_code.jpg')" alt="支付二维码">
          </div>
          <p class="qrcode-tip">请使用{{ payMethod === 'alipay' ? '支付宝' : '微信' }}扫一扫</p>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handlePay(2);payDialogVisible = false">取消支付</el-button>
          <el-button type="primary" @click="handlePay(3)">支付完成</el-button>
        </span>
      </template>
    </el-dialog>

</template>
  
<script>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { useRouter } from 'vue-router';
export default {
  setup() {
    const router = useRouter()
    //当前页码
    const currentPage = ref(1)
    //总条数
    const total = ref(0)
    //总页数
    const pageCount = ref(0)
    const searchText = ref('')
    const pageSize = ref(6)
    const scenicList = ref([])
    const payDialogVisible = ref(false)
    const scenicInfo = ref({})
    const loading = ref(false)
    const payMethod = ref('wechat') // 默认选中微信支付

    //跳转详情页
    const goInfo = (id) => {
      router.push(`/travel-info/${id}`)
    }

    const orderId = ref('')

    const handleSearch = () => {
      // 搜索时重置页码到第一页
      currentPage.value = 1
      if(searchText.value.trim() === '') {
        // 如果搜索框为空，加载所有数据
        scenicQueryPage()
        return
      }
      
      loading.value = true
      // 根据名称搜索景区
      axios.get('/api/scenic/like/name', {
        params: {
          name: searchText.value,
          pageNum: currentPage.value,
          pageSize: pageSize.value
        }
      })
      .then(res => {
        loading.value = false
        if(res.data.code === 200) {
          const data = res.data.data
          scenicList.value = data.data
          total.value = data.total
          pageCount.value = data.pageCount
          ElMessage.success('搜索完成')
        } else {
          ElMessage.error(res.data.message || '搜索失败')
        }
      })
      .catch(err => {
        loading.value = false
        ElMessage.error('搜索请求失败')
      })
    }

    const handleBook = (item) => {
      // 实现预订逻辑
      const user = checkLogin()
      if(user === '') {
        return
      }

      if(item.ticketPrice === 0){
        ElMessage.success('该景区是免费的直接前往即可')
      }else{
        scenicInfo.value = item
        //创建订单获取订单号
        axios.post('/api/ticket/order',{
          userId: user.id,
          scenicId: item.id,
        })
        .then(res => {
          if(res.data.code === 200){
            const orderNumber = res.data.data
            orderId.value = orderNumber
            ElMessage.success("订单创建成功！您的单号："+orderNumber)
            showPayDialog(item.id)
          }
        })
        .catch(err => {
          ElMessage.error(err.response.data.message)
        })
      }
    }

    const showPayDialog = (id) => {

      if(id === ''){
        ElMessage.warning('订单未创建成功')
        return
      }

      if(scenicInfo.ticketPrice === 0){
        ElMessage({
            message: "该景区是免费的直接前往即可",
            type: 'success',
          })
        return
      }else{
        const user = checkLogin()
        if(user === '') {
          return
        }
        payDialogVisible.value = true
      }
    }

    const handlePay = (state) => {
      const user = checkLogin()
      if(user === '') {
        return
      }
      axios.post('/api/ticket/pay',{
        orderNumber: orderId.value,
        state: state,
      })
      .then(res => {
        if(res.data.code === 200){
          if(state === 3){
            ElMessage.success("支付成功！您可以前往个人中心查看订单详情")
          }else{
            ElMessage.success("取消支付")
          }
          payDialogVisible.value = false
        }else{
          ElMessage.error(res.data.message)
        }
      })
      .catch(err => {
        ElMessage.error(err.response.data.message)
      })
    }

    const handlePageChange = (page) => {
      currentPage.value = page
      // 如果有搜索文本，则按搜索条件分页，否则获取所有数据
      if(searchText.value.trim() !== '') {
        handleSearch()
      } else {
        scenicQueryPage()
      }
    }

    onMounted(() => {
      // 初始化加载数据
      scenicQueryPage()
    })

    const scenicQueryPage = function(){
      axios.get('/api/scenic/all/page',{
        params:{
          pageNum: currentPage.value,
          pageSize: pageSize.value
        }
      })
      .then(res => {
        if(res.data.code === 200){
          const data = res.data.data
          scenicList.value = data.data
          total.value = data.total
          pageCount.value = data.pageCount
        }else{
          ElMessage({
            message: res.data.message,
            type: 'error',
          })
        }
      }).catch(err => {
        ElMessage({
          message: "获取数据失败!",
          type: 'error',
        })
      })
    }

    const checkLogin = () => {
      const user = JSON.parse(sessionStorage.getItem('userInfo'))
      if(user === null || user === undefined || user === '') {
        ElMessage.error('请先登录')
        return ''
      }
      return user
    }

    // 选择支付方式
    const selectPayMethod = (method) => {
      payMethod.value = method
    }

    return {
      searchText,
      scenicList,
      currentPage,
      total,
      pageCount,
      pageSize,
      loading,
      handleSearch,
      handleBook,
      handlePageChange,
      goInfo,
      checkLogin,
      showPayDialog,
      handlePay,
      payDialogVisible,
      scenicInfo,
      payMethod,
      selectPayMethod
    }
  }
}
</script>

<style scoped>

.pay-dialog-content {
  text-align: center;
}
.travel-container {
  padding: 20px;
}

.search-area {
  display: flex;
  justify-content: center;
  margin-bottom: 30px;
}

.search-input {
  width: 300px;
  margin-right: 10px;
}

.scenic-list {
  margin-bottom: 30px;
}

.scenic-card {
  margin-bottom: 20px;
  transition: all 0.3s;
}

.scenic-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.scenic-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
}

.scenic-info {
  padding: 10px;
}

.desc {
  color: #666;
  font-size: 14px;
  margin: 10px 0;
}

.price-area {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price {
  color: #f56c6c;
  font-size: 20px;
  font-weight: bold;
}

.pagination {
  display: flex;
  justify-content: center;
  margin: 30px 0;
}

.alipay-style-dialog {
  padding: 0;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}

.alipay-header {
  display: flex;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 20px;
}

.alipay-logo {
  width: 30px;
  height: 30px;
  margin-right: 10px;
}

.alipay-title {
  font-size: 18px;
  font-weight: bold;
  color: #00a0e9;
}

.order-details {
  background-color: #f8f8f8;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 20px;
}

.order-info {
  margin-bottom: 10px;
}

.order-name {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 5px;
}

.order-number {
  font-size: 12px;
  color: #999;
}

.order-price {
  text-align: center;
  margin: 15px 0;
}

.price-symbol {
  font-size: 20px;
  font-weight: bold;
  color: #333;
}

.price-value {
  font-size: 30px;
  font-weight: bold;
  color: #333;
}

.payment-methods {
  margin-bottom: 20px;
}

.payment-method-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}

.payment-method-item {
  display: flex;
  align-items: center;
  padding: 12px 15px;
  border: 1px solid #f0f0f0;
  border-radius: 4px;
  cursor: pointer;
  margin-bottom: 10px;
}

.payment-method-item.selected {
  border-color: #00a0e9;
  background-color: #f7fcff;
}

.method-icon {
  width: 24px;
  height: 24px;
  background-position: center;
  background-repeat: no-repeat;
  background-size: contain;
  margin-right: 10px;
}

.alipay-icon {
  background-image: url(https://img.alicdn.com/imgextra/i1/O1CN01R0YN9T1nN1BCkqP5Y_!!6000000005072-2-tps-140-140.png);
}

.wechat-icon {
  background-image: url(https://res.wx.qq.com/a/wx_fed/assets/res/NTI4MWU5.ico);
}

.method-name {
  flex: 1;
  font-size: 14px;
}

.method-check {
  width: 16px;
  height: 16px;
  border-radius: 50%;
  border: 1px solid #00a0e9;
  position: relative;
}

.method-check.active::after {
  content: '';
  position: absolute;
  width: 8px;
  height: 8px;
  background-color: #00a0e9;
  border-radius: 50%;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.alipay-qrcode {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 20px 0;
}

.qrcode-container {
  padding: 10px;
  border: 1px solid #f0f0f0;
  border-radius: 4px;
  margin-bottom: 10px;
}

.qrcode-tip {
  font-size: 14px;
  color: #666;
}

</style>